"""
用户偏好和画像API路由
提供用户个性化服务相关的API端点
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, List, Dict, Any
import uuid
from sqlalchemy.orm import Session
from src.config.database import get_db
from src.models.user_preference import (
    UserPreferenceResponse, 
    UserPreferenceUpdate, 
    UserProfileResponse,
    UserProfileUpdate,
    RecommendationsResponse
)
from src.services.user_profile_service import UserProfileService
from src.services.auth_service import get_current_user_dep as get_current_user
from src.models.user import User
from src.exceptions import UserNotFoundError, DatabaseError
from src.utils.logging import get_logger

# 获取日志记录器
logger = get_logger(__name__)

router = APIRouter(
    prefix="/user/preferences",
    tags=["User Preferences"],
    responses={404: {"description": "Not found"}}
)


@router.get("/", response_model=UserPreferenceResponse, summary="获取用户偏好设置")
async def get_user_preferences(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的偏好设置
    
    Returns:
        用户偏好设置信息
    """
    try:
        service = UserProfileService(db)
        preference = service.get_user_preference(current_user.id)
        if not preference:
            raise HTTPException(status_code=404, detail="用户偏好不存在")
        return preference
    except UserNotFoundError:
        raise HTTPException(status_code=404, detail="用户不存在")
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户偏好失败: {str(e)}")


@router.put("/", response_model=UserPreferenceResponse, summary="更新用户偏好设置")
async def update_user_preferences(
    preferences: UserPreferenceUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    更新当前用户的偏好设置
    
    Args:
        preferences: 用户偏好更新数据
        
    Returns:
        更新后的用户偏好设置
    """
    try:
        service = UserProfileService(db)
        # 将Pydantic模型转换为字典，并过滤掉None值
        update_data = preferences.dict(exclude_unset=True)
        updated_preference = service.update_user_preference(current_user.id, update_data)
        if not updated_preference:
            raise HTTPException(status_code=404, detail="用户偏好不存在")
        return updated_preference
    except UserNotFoundError:
        raise HTTPException(status_code=404, detail="用户不存在")
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新用户偏好失败: {str(e)}")


@router.get("/profile", response_model=UserProfileResponse, summary="获取用户画像")
async def get_user_profile(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的画像信息
    
    Returns:
        用户画像信息
    """
    try:
        service = UserProfileService(db)
        profile = service.get_user_profile(current_user.id)
        if not profile:
            raise HTTPException(status_code=404, detail="用户画像不存在")
        return profile
    except UserNotFoundError:
        raise HTTPException(status_code=404, detail="用户不存在")
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户画像失败: {str(e)}")


@router.put("/profile", response_model=UserProfileResponse, summary="更新用户画像")
async def update_user_profile(
    profile_update: UserProfileUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    更新当前用户的画像信息
    
    Args:
        profile_update: 用户画像更新数据
        
    Returns:
        更新后的用户画像信息
    """
    try:
        service = UserProfileService(db)
        # 将Pydantic模型转换为字典，并过滤掉None值
        update_data = profile_update.dict(exclude_unset=True)
        updated_profile = service.update_user_profile(current_user.id, update_data)
        if not updated_profile:
            raise HTTPException(status_code=404, detail="用户画像不存在")
        return updated_profile
    except UserNotFoundError:
        raise HTTPException(status_code=404, detail="用户不存在")
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新用户画像失败: {str(e)}")


@router.get("/recommendations", response_model=RecommendationsResponse, summary="获取个性化推荐")
async def get_recommendations(
    limit: int = Query(5, ge=1, le=20, description="推荐数量限制"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的个性化推荐内容
    
    Args:
        limit: 推荐数量限制 (1-20)
        
    Returns:
        个性化推荐内容列表
    """
    try:
        service = UserProfileService(db)
        recommendations = service.get_recommendations(current_user.id, limit)
        return recommendations
    except Exception as e:
        logger.error(f"获取个性化推荐失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取个性化推荐失败: {str(e)}")


@router.post("/interactions", summary="记录用户内容交互")
async def record_user_interaction(
    interaction: dict,  # 简化处理，实际应该定义专门的Pydantic模型
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    记录用户与内容的交互行为
    
    Args:
        interaction: 交互数据，包含content_id、interaction_type和score
        
    Returns:
        操作结果
    """
    try:
        from src.services.recommendation_service import get_recommendation_service
        
        content_id = interaction.get("content_id")
        interaction_type = interaction.get("interaction_type")
        score = interaction.get("score", 0.0)
        
        if not content_id or not interaction_type:
            raise HTTPException(status_code=400, detail="缺少必要参数")
        
        # 初始化推荐服务
        recommendation_service = get_recommendation_service(db)
        
        # 记录用户交互
        recommendation_service.record_user_interaction(
            str(current_user.id), 
            content_id, 
            interaction_type, 
            score
        )
        
        return {"status": "success", "message": "交互记录已保存"}
    except Exception as e:
        logger.error(f"记录用户交互失败: {e}")
        raise HTTPException(status_code=500, detail=f"记录用户交互失败: {str(e)}")
